#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread1(void *arg)
{
    printf("thread1 is running...\n");
    int *p = new (int);
    *p = 1;
    return (void *)p; //
}

void *thread2(void *arg)
{
    printf("thread2 is exiting...\n");
    int *p = new (int);
    *p = 2;
    pthread_exit((void *)p); //
}

void *thread3(void *arg)
{
    while (1)
    {
        printf("thread3 is running...\n");
        sleep(1);
    }
    return NULL; //
}

int main()
{
    pthread_t tid;
    void *ret;

    // 1. return thread
    pthread_create(&tid, NULL, thread1, NULL);// 分别是线程id 线程属性 线程函数指针 线程函数需要传入的参数
    pthread_join(tid, &ret);
    printf("thread return ,and the thread id is [%d],the return code is [%d]\n", tid, *(int *)ret); //!!!! 先转int 再解引用
    free(ret);

    // 2. exit thread
    pthread_create(&tid, NULL, thread2, NULL);
    pthread_join(tid, &ret);
    printf("thread return ,and the thread id is [%d],the return code is [%d]\n", tid, *(int *)ret); //!!!! 先转int 再解引用
    free(ret);

    // 3. cancel by other
    pthread_create(&tid, NULL, thread3, NULL);
    sleep(3);

    pthread_cancel(tid);
    pthread_join(tid, &ret);

    if (ret == PTHREAD_CANCELED)
    {
        printf("thread3 return ,and the thread id is [%d],the return code is PTHREAD_CANCELED\n", tid);
    }
    else
    {
        printf("thread3 return ,and the thread id is [%d],the return code is [%d]\n", tid, *(int *)ret);
    }
    free(ret);

    return 0;
}
